package com.xo.user.controller;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;

import java.util.Collection;
import java.util.Objects;

/**
 * 自定义登录用户信息，扩展Spring Security的User类
 */
public class LoginUser extends User {

    // 租户ID，使用private修饰保证封装性
    private final Long tenantId;

    // 新增含tenantId的构造方法，强制初始化租户ID
    public LoginUser(String username, String password, Collection<? extends GrantedAuthority> authorities, Long tenantId) {
        super(username, password, authorities);
        // 校验租户ID非空（根据业务需求决定是否强制非空）
        if (tenantId == null) {
            throw new IllegalArgumentException("租户ID(tenantId)不能为空");
        }
        this.tenantId = tenantId;
    }

    // 保留其他必要的构造方法（按需提供）
    public LoginUser(String username, String password, boolean enabled,
                     boolean accountNonExpired, boolean credentialsNonExpired,
                     boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities,
                     Long tenantId) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
        this.tenantId = tenantId;
    }

    // 只提供getter，不提供setter，保证tenantId不可修改
    public Long getTenantId() {
        return tenantId;
    }

    // 重写equals和hashCode，确保包含tenantId的比较
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        if (!super.equals(o)) return false;
        LoginUser loginUser = (LoginUser) o;
        return Objects.equals(tenantId, loginUser.tenantId);
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), tenantId);
    }

    // 重写toString，避免敏感信息泄露，同时包含tenantId便于日志排查
    @Override
    public String toString() {
        return "LoginUser{username='" + getUsername() + "', tenantId=" + tenantId + "}";
    }
}
